package com.projectfixit.web;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.projectfixit.dao.AuthDao;
import com.projectfixit.entity.AuthDO;

public class AuthLogin extends HttpServlet {
	private static final long serialVersionUID = -5589398999865825828L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");

		HttpSession session = request.getSession();
		if (email != null && !email.isEmpty()) {
			AuthDao authDao = new AuthDao();
			AuthDO authdo = authDao.getAuthDO(email);
			if (authdo != null) {
				MessageDigest messageDigest;
				try {
					messageDigest = MessageDigest.getInstance("MD5");
					byte[] matchPasswordBytes = messageDigest.digest(password.getBytes());
					if (authdo.isEquals(matchPasswordBytes)) {
						session.setAttribute("login", "true");
						session.setAttribute("logsuccessful", "true");
						// request.getRequestDispatcher("/WEB-INF/author/report.jsp");
						response.sendRedirect("/report.jsp");
					}
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				}
			}
		}

		session.setAttribute("logsuccessful", "false");
		response.sendRedirect("/register.jsp");
	}
}
